<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\CemeteryModel;
use app\admin\model\ContractModel;
use app\admin\model\CustomerInfoModel;
use app\admin\model\OrderGoodsModel;
use app\admin\model\OrderModel;
use app\admin\model\OrderPayLogModel;
use app\admin\model\PayDepositModel;
use app\admin\model\TombareaInformationProductModel;
use app\admin\model\TombareaRowColModel;
use cmf\controller\AdminBaseController;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use app\admin\model\AdminMenuModel;
use tree\Tree;

class OrdersController extends AdminBaseController
{
//状态0-无产品、1-空闲、2-已认购、3-定金、4-无规划、5-购买未使用，6-部分安葬、7全部安葬、8迁出

    protected $selected_id = 0;
    protected $cemetery_model;
    public function initialize(){
        $this->deal_model=Db::name("orders");
        $this->selected_id = session('selected_id');
        $this->cemetery_model = new CemeteryModel();
        parent::initialize();
    }

    /*订单列表*/
	public function index(){
        $data = $this->request->param('customer_name');
        $data1 = $this->request->param('customer_phone');
        $orders_id = OrderModel::where('orders_id','neq','0')->column('orders_id');
        $where = "c.order_status = 1";
        $orders_id = implode(',',$orders_id);
        if ($orders_id){
            $where.=" and c.id  not in({$orders_id})";
        }
        $results = Db::name('orders')->alias('c')
            ->field('c.*,c.id tid,u.user_nickname,o.order_id,t.cate_id,t.col_status')
            ->leftJoin('dj_order o','c.id = o.orders_id')
            ->leftJoin('dj_tombarea_row_col t','t.colID = c.tomb_id')
            ->join('dj_user u','u.id=c.edit_user')
            ->where('c.customer_name','like','%'.$data.'%')
            ->where('c.customer_phone','like','%'.$data1.'%')
            ->where($where)
            ->order('c.id', 'DESC')->paginate(15);
        $page = $results->render();
        $this->assign("results",$results);
        $this->assign("page", $page);

		return $this->fetch();
	}

    /*订单跳转添加*/
    public function addorders(){

        $users = Db::name("user")->alias('u')->field('u.id,user_nickname')
            ->join('dj_department c','c.id=u.dept_id')
            ->where(['u.user_type'=>'2','c.dept_type'=>'1'])
            ->select();

        $this->assign("userlist", $users);

        return $this->fetch();
    }

    /*订单添加保存*/
    public function add_post(){

        $data           = $this->request->param();
        //只有空闲状态的墓位才可以销售
        $tomb = Db::name("tombarea_row_col")->field('col_status')->where('colID',$data['tomb_id'])->find();

        if($tomb['col_status'] != 1){
            $this->error('只能下单空闲的墓位!');
        }

        $ymd = date('YmdHi',time());

        $data['order_sn'] = 'PC_'.$ymd.'_'.mt_rand(0001, 9999);
        $data['sell_time'] =strtotime($data['sell_time']);
        $data['end_time'] =strtotime($data['end_time']);
        $data['add_time'] =time();
        $data['edit_user'] =cmf_get_current_admin_id();
        $data['order_status'] = '1';
        $this->deal_model->insert($data);

        $this->success("添加成功！", url("orders/index"));
    }
    /*订单管理-取消订单*/
    public function cancel()
    {
        $id = $this->request->param("id");
        $tomb_num = $this->request->param("tomb_num");

        $saveData =  $this->deal_model->where('id', $id)->find();
        $saveData['order_status'] ='2';
        $this->deal_model->update($saveData);

        // 更新墓位主表的状态为空闲
        $data11 =  Db::name("tombareaRowCol")->where('num', $tomb_num)->find();
        if(!empty($data11)){
            $data11['col_status'] = 1;
            Db::name("tombareaRowCol")->update($data11);
        }

        $this->success("取消成功", url("orders/index"));
    }

    //获取墓位编号信息
    public function getTombInfo($tomb_num){
        $result = Db::name('tombarea_information_product')
            ->field("tomb_id,tomb_region,selling_price")
            ->where(['tomb_num'=>$tomb_num])
            ->find();
        return json($result);
    }

	/*可视化*/
    public function visua(){
        $name = $this->request->param("name");
        $orders_id = $this->request->param("orders_id",0);
        if(empty($name)){
            $result = $this->cemetery_model->cacheCemeteryData();
        }else{
            $result =  $this->cemetery_model->alias("c")
                ->field("c.id,c.name,c.parent_id as pId,c.type")
                ->join("dj_tombarea t","c.id = t.cemetery_id","left")
                ->join("dj_tombarea_row r","t.id = r.tombarea_id","left")
                ->join("dj_tombarea_row_col rc","r.rowID = rc.rowid","left")
                ->join("dj_archives_deceased d","d.tomb_id = rc.colID","left")
                ->where('c.is_delete',0)
                ->where('rc.num',$name)
                ->whereOr('d.deceased_name',"like","%".$name."%")
                ->order(array("c.list_order" => "ASC"))
                ->select()->toArray();
        }

        $tom = array();
        foreach($result as $k => $v){
            $tombarea = Db::name("tombarea")->field("id,name,'' as type")
                ->where(array("cemetery_id"=>$v["id"],"status"=>1))->order('list_order asc ')
                ->select()->toArray();
            foreach($tombarea as $i => $t){
                $tombarea[$i]['pId'] = $v["id"];
            }
            $tom = array_merge_recursive ( $tom, $tombarea);
        }
        $result = array_merge_recursive ( $tom, $result);

        $this->assign("categorys", json_encode($result));
        $this->assign("orders_id", $orders_id);
        $this->assign("name", $name);
        //选中的ID
        $this->assign("selected_id", $this->selected_id?$this->selected_id:0);
        return $this->fetch();
    }

//	/*购买*/
	public function sale(){
	    $request = $this->request;
	    if ($this->request->isPost()){
	        $ajax = $request->param('ajax',0);
	        if ($ajax==1){
                $orders_id = $request->param('orders_id',0);
                $mw_id = $request->param('mw_id',0);
               $info =  TombareaInformationProductModel::where(['tomb_id'=>$mw_id])->find();
               Db::name('orders')->where(['id'=>$orders_id])->update(['tomb_id'=>$mw_id,'tomb_num'=>$info['tomb_num'],
                   'sell_price'=>$info['selling_price'],
                   'tomb_address'=>$info['tomb_region'].$info['tomb_address'].$info['layer_num'].$info['tomb_bit_number']]);
               return $this->success('换位成功。',url('index'));
            }
	        $parem = $request->param();
	        $insert_order = $parem['order'];
	        $update_tomb = isset($parem['tomb'])?$parem['tomb']:'';
	        $update_tomb_mb = isset($parem['tm_mb_id'])?$parem['tm_mb_id']:'';
            $tomb_id = $insert_order['tomb_id'];
            if (!$insert_order['order_id']) {
                $insert_order['archives_sn'] = date('Ymdhis');
                $insert_order['closing_time'] = time();
                $insert_order['add_time'] = strtotime($parem['add_time']);
                $insert_order['handle'] = cmf_get_current_admin_id();
            }
            if ($insert_order['tomb_type']!=2 || $insert_order['tomb_type']!=4 ){
                $insert_order['sales_total'] = $insert_order['selling_price'];
            }
            $col_updata = [
                'manage_cycle'=>isset($parem['manage_cycle'])?$parem['manage_cycle']:'',//管理期
            ];
            if (isset($update_tomb['funeral'])){
                $col_updata['funeral']=$update_tomb['funeral'];
            }
            if (isset($update_tomb['convergence'])){
                $col_updata['convergence']=$update_tomb['convergence'];
            }
            if (isset($update_tomb['single_cavity_size'])){
                $col_updata['single_cavity_size']=$update_tomb['single_cavity_size'];
            }
            if (isset($update_tomb['accommodate_outfit'])){
                $col_updata['accommodate_outfit']=$update_tomb['accommodate_outfit'];
            }
            if (isset($update_tomb['storage_way'])){
                $col_updata['storage_way']=$update_tomb['storage_way'];
            }
            if (isset($update_tomb['tomb_regulation'])){
                $col_updata['tomb_regulation']=$update_tomb['tomb_regulation'];
            }
            Db::name("tombarea_information_product")->where(['id'=>$insert_order['tomb_product_id']])->update($col_updata);

	        if ($insert_order['order_id']){
                $order_id = $insert_order['order_id'];
                unset($insert_order['order_id']);
                $insert_order['handle'] = cmf_get_current_admin_id();
                Db::name('order')->where(['order_id'=>$order_id])->update($insert_order);
            }else{
                $order_id = Db::name('order')->insertGetId($insert_order);
            }
           if ($order_id){
               TombareaRowColModel::update(['col_status'=>2],['colID'=>$tomb_id,'col_status'=>1]);
               if ($update_tomb_mb){
                   Db::name("tomb_mb")->where(['tomb_id'=>$tomb_id])->update(['status'=>0]);
                   foreach ($update_tomb_mb as $k){
                       Db::name("tomb_mb")->where(['id'=>$k])->update(['status'=>1]);
                   }
               }else{
                   Db::name("tomb_mb")->where(['tomb_id'=>$tomb_id])->update(['status'=>0]);
               }
               return $this->success('提交成功',url("applyer",['order_id'=>$order_id]));
           }else{
               $this->error('提交失败',url("sale",['tomb_id'=>$tomb_id,'order_id'=>$order_id]));
           }
        }

	    $parem = $this->request->param();
        session('selected_id', isset($parem['selected_id'])?$parem['selected_id']:'0');
	    $tomb_id = isset($parem['tomb_id'])?rtrim($parem['tomb_id'],','):'';
	    $orders_id = isset($parem['orders_ids'])?$parem['orders_ids']:'0';// 售前订单id
	    $order_id = isset($parem['order_id'])?$parem['order_id']:'';
        $type = $this->request->param('type');
        $this->assign("orders_id",$orders_id);
        $this->assign("type",$type);

	    if ($order_id){
            $tomb_info = Db::name("order")->alias("o")
                ->join("tombarea_row_col c","o.tomb_id = c.colID ","left")
                ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id","left")
                ->whereIn('o.order_id',$order_id)->find();
            $tomb_id = $tomb_info['tomb_id'];
            $tomb_info['shoppingguide_name'] = cmf_get_admin_name($tomb_info['shoppingguide']);
            $tomb_info['handle_name'] = cmf_get_admin_name(isset($tomb_info['handle'])?$tomb_info['handle']:'');
//            $tomb_info['agent_user'] = cmf_get_admin_name(isset($tomb_info['agent_user'])?$tomb_info['agent_user']:'');

        }else{
            $tomb_info = Db::name("tombarea_row_col")->alias("c")
                ->join("dj_tombarea_information_product p","c.colID = p.tomb_id","left")
                ->whereIn('c.colID',$tomb_id)->find();

            if ($orders_id){
                $orders_info = Db::name('orders')->where(['id'=>$orders_id])->find();
                $tomb_info['shoppingguide_name'] = cmf_get_admin_name($orders_info['edit_user']);
                $tomb_info['shoppingguide'] = $orders_info['add_user'];
            }else{
                $tomb_info['shoppingguide_name'] = cmf_get_admin_name();
                $tomb_info['shoppingguide'] = cmf_get_current_admin_id();
            }
            $tomb_info['handle'] = cmf_get_current_admin_id();
            $tomb_info['handle_name'] = cmf_get_admin_name();
//            $tomb_info['agent_user'] = cmf_get_current_admin_id();
        }

        $num='';
        if ($tomb_info){
            if ($tomb_info['single_cavity_size']) {
                $single_cavity_size = explode('*', $tomb_info['single_cavity_size']);
                $tomb_info['sc_width'] = $single_cavity_size[0];
                $tomb_info['sc_height'] = $single_cavity_size[1];
                $tomb_info['sc_thick'] = $single_cavity_size[2];
            }
            $num  = $tomb_info['num'];
            $cate_id = $tomb_info['cate_id'];
        }

//        // 石材种类
        $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")-> join("dj_cate c","c.id = s.cate_id","left") ->select();
        $this->assign("cate_type",json_encode($cate_type));

//        // 附件
        $annex = Db::name("annex")->field("id,annex_name as name")->select();
        $this->assign("annexJson", json_encode($annex));

        $mblist=  Db::name('product')->where('pro_type', $cate_id)->select();
        $user = Db::name("user")->alias('u')->field('u.*,d.department_name')
            ->join('dj_department d', 'd.id=u.dept_id')
            ->order('d.department_name', 'DESC')
            ->select();
        // 只查代理商的人員
        $dailishang_list = Db::name("user")->alias('u')->field('u.*,d.department_name')
            ->join('dj_department d', 'd.id=u.dept_id')
            ->where("d.dept_type","8")
            ->order('d.department_name', 'DESC')
            ->select();

        $this->assign("users", $user);
        $this->assign([
            'order_id'=>$order_id,
            'cate_id'=>$cate_id,
            'num_sn'=>$num,
            'col_id'=>$tomb_id,
            'mb_list'=>$mblist,
            'cate_name'=>$this->cate_arr[$cate_id],
            'admin_name'=> cmf_get_admin_name(),
            'agent_user'=>'',
            'handle'=>'',
            'user_list'=>$user,
            'dailishang_list'=>$dailishang_list,
        ]);
        $tomb_info['tomb_status'] = $this->col_status[$tomb_info['col_status']];
        $tomb_info['add_order_time'] = date('Y-m-d H:i',time());
        $this->this_tomb();
//        dump($tomb_info);exit;
        if ($cate_id==1){
            $this->assign('result',$tomb_info);

            return $this->fetch('tomb_commodity_sale');//商品墓
        }else if ($cate_id==2){

            $tomb_info['baseData']    = Db::name("tomb_mb")->alias("tm")
                ->join("product_mb mb","tm.mb_id = mb.id")
////                ->join("product p","pmb.product_id = p.id","left")
                ->field('tm.*')
                ->where(['tm.tomb_id'=>$tomb_info['tomb_id'],'type'=>0])->select();
            $cate_typed = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")->join("dj_cate c", "c.id = s.cate_id", "left")->select();
            $this->assign("cate_type", $cate_typed);
            $product_info= Db::name("tomb_mb")->alias("tm")
                ->join("product_mb_info mbi","tm.mb_info_id = mbi.id")
                ->field('mbi.*,tm.id tm_mb_id,tm.status')
                ->where(['tomb_id'=>$tomb_info['tomb_id'],'type'=>7])->select();

            $tomb_info['product_mb_base'] = Db::name('product_mb_base')->where('product_id', $tomb_info['new_pro'])->select();
            $tomb_info['product_info'] = $product_info;

            $this->assign('result',$tomb_info);
            return $this->fetch('tomb_arl_sale');
        }else if ($cate_id==3){
            $this->assign('result',$tomb_info);
            return $this->fetch('tomb_ecological_sale');//生态墓
        }else if ($cate_id==4){

            $tomb_infos = Db::name("tombarea_row_col")->alias("c")
                ->join("dj_tombarea_row tr","c.rowid = tr.rowID","left")
                ->join("dj_tombarea t","tr.tombarea_id = t.id","left")
                ->field('tr.column row_column,tr.tombarea_id,t.name tombarea_name,t.cemetery_id')
                ->whereIn('c.colID',$tomb_id)->find();

           $cemetery_id = $this->getParent($tomb_infos['cemetery_id']);

            $tomb_info['row_column'] =$tomb_infos['row_column'];
            $tomb_info['weizhi'] =$cemetery_id;

            $this->assign('result',$tomb_info);
            return $this->fetch('tomb_festival_sale');//节地墓
        }
		return $this->fetch();
	}

    /*购墓人信息*/
    public function applyer()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (!idcard_verify_number($data['customer_account'])){
               return $this->error('证件号格式不正确');
            }
            $validate=validate("CustomerInfo");
            if (isset($data['is_show'])){
                $is_validate = $validate->scene("is_show_save")->check($data);
            }else{
                $is_validate = $validate->scene("save")->check($data);
            }

            if(!$is_validate){
                return $this->error($validate->getError());
            }
            $order_id = $data['order_id'];
            $customer_id = $data['customer_id'];
            $dtype = $data['dtype'];
            unset($data['dtype']);
            unset($data['customer_id']);
            unset($data['order_id']);
            if ($customer_id){
                $order_customer_id = $customer_id;
                $customer_id = Db::name("customer_info")->where(['id'=>$customer_id])->update($data);
            }else{
                $data['add_time'] = time();
                $data['add_user'] = cmf_get_current_admin_id();
                $customer_id = Db::name("customer_info")->insertGetId($data);
                $order_customer_id = $customer_id;
            }
            Db::name('order')->where(['order_id'=>$order_id])->update(['customer_id' => $order_customer_id]);
            if ($dtype==1){
                $this->success("保存成功", url("deposit", ['customer_id' => $order_customer_id,'order_id'=>$order_id]));
            }else{
                $this->success("保存成功", url("chooseGoods", ['customer_id' => $order_customer_id,'order_id'=>$order_id]));
            }
        }
        $data = $this->request->param();


        $dj_count =  PayDepositModel::where(['order_id'=>$data['order_id']])->count();

        $order_info = Db::name("order")->where(['order_id'=>$data['order_id']])->find();
        $result_info = Db::name("customer_info")->where(['id'=>$order_info['customer_id']])->find();
        $result_info['shoppingguide'] = cmf_get_admin_name(isset($result_info['shoppingguide'])?$result_info['shoppingguide']:'');
        $this->assign([
            'order_id'=>$data['order_id'],
            'result'=>$result_info,
            'dj_count'=>$dj_count,
            'order_info'=>$order_info,
            'tomb_num'=>$order_info['tomb_num'],
            'tomb_type_name'=>$this->cate_arr[$order_info['tomb_type']],
        ]);
        return $this->fetch();
    }
    //定金
    public  function deposit(){
        if ($this->request->isPost()){
            $data = $this->request->param();
            $PayDepositModel =new PayDepositModel();
            $result = $PayDepositModel->doAddDate($data);
            if ($result){
                $this->success('提交定金成功',url('visua'));
            }else{
                $this->error($PayDepositModel->getError());
            }
        }
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $field='o.order_id,o.tomb_id,o.tomb_num,o.tomb_type,o.closing_price,o.orders_id,
            p.tomb_regulation,
            o.customer_id,ci.buyer_name,ci.buyer_phone';
        $order_info = Db::name('order')->alias('o')->field($field)
            ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id","left")
            ->join("dj_customer_info ci","o.customer_id = ci.id")
            ->where(['o.order_id'=>$order_id])->find();
        $customer_id = $order_info['customer_id'];
        $result_list = Db::name('archives_deceased')->where(['order_id'=>$order_id])->select();


        $this->assign([
            'order_info'=> $order_info,
            'deposit_price'=> $order_info['closing_price'] *0.3,
            'order_id'=>$order_id,
            'result_list'=>$result_list,
            'end_time'=>date("Y-m-d H:i:s", strtotime("+30 day")),
        ]);

        if ($order_info['tomb_type']==2){
            return $this->fetch('deposit_arl');
        }else{
            return $this->fetch();
        }
    }

    /*商品选购*/
    public function chooseGoods(){
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (isset($param['goods'])) {
                $model = new OrderGoodsModel();
                $result = $model->doAddData($param);

                if ($result) {
                    return $this->success('提交成功', url('signcontract', ['customer_id' => $param['customer_id'], 'order_id' => $param['order_id']]));
                } else {
                    return $this->error($model->getError());
                }
            }else{
                return $this->success('提交成功', url('signcontract', ['customer_id' => $param['customer_id'], 'order_id' => $param['order_id']]));
            }
        }

        $data = $this->request->param();
        $result = Db::name('order_goods')->where(['customer_id'=>$data['customer_id'],'order_id'=>$data['order_id']])->select();

        //2为商品类型
        $where = array('d.type' => 2, 'd.is_delete' => 0, 'parent_id' => 0);
        //取库房数据
        $results_cate = Db::name("Cate")->alias('d')->where($where)->order('sort_order ASC,d.id DESC')->select();
        $this->assign("results_cate", $results_cate);
        $this->assign("order_id", $data['order_id']);
        $this->assign("customer_id", $data['customer_id']);
        $this->assign("is_shouxue", isset($data['is_shouxue']));
        $this->assign("deceased_id", isset($data['deceased_id']));
        $this->assign("result", $result);
//        $this->assign("tomb_type_name", isset($data['deceased_id']));

        return $this->fetch('chooseGoods');
    }
	/*合同*/
	public function signcontract(){
	    if ($this->request->isPost()){
            $param = $this->request->param();

            if (!empty(session('sign_time'))) {
                session('sign_time',$param['sign_time']);
                if (empty($param['contract_enclosure'])){
                    return $this->error('上传签章合同');
                }else{
                    session('sign_time','');
                }
            }
            $result_order = Db::name('order')->where(['order_id'=>$param['order_id']])->find();
            $insert = [
                'tomb_type'=>$result_order['tomb_type'],
                'tomb_id'=>$result_order['tomb_id'],
                'contract_enclosure'=>$param['contract_enclosure'],
                'contract_enclosure_file_id'=>$param['contract_enclosure_file_id'],
                'supplement'=>$param['supplement'],
                'supplement_file_id'=>$param['supplement_file_id'],
                'keep_record_time'=>strtotime($param['keep_record_time']),
                'sign_time'=>strtotime($param['sign_time']),
                'add_time'=>time(),
            ];
            Db::name('contract')->where(['contract_sn'=>$param['contract_sn']])->update($insert);//->insertGetId($insert);
           $res = Db::name('order')->where(['order_id'=>$param['order_id']])->update([
                    'contract_sn'=>$param['contract_sn'],
                    'sign_time'=>strtotime($param['sign_time']),
                    'dz_time'=>strtotime($param['sign_time']),
                    'sj_time'=>strtotime($param['sign_time']),
                    'add_time'=>time(),
                ]);
            $file =  ContractModel::content_temp($param['order_id'],$param['contract_sn'],strtotime($param['sign_time']));
           if ($res){
               return $this->success('提交成功');
           }else{
               return $this->error('操作失败！');
           }


//            $this->success('提交成功',url('Orderpay',['order_id'=>$param['order_id']]));
        }
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $customer_id = $data['customer_id'];

        $con_is = Db::name('contract')->where(['order_id'=>$order_id])->find();

        if (!$con_is){
            $contract_sn = ContractModel::get_contract_sn();
            $file =  ContractModel::content_temp($order_id,$contract_sn);
            Db::name('contract')->insertGetId(['order_id'=>$order_id,'contract_sn'=>$contract_sn,
                'contract_file'=>json_encode($file),'keep_record_time'=>time(),'add_time'=>time(),'customer_id' => $customer_id]);
        }else{
//                $file =  ContractModel::content_temp($order_id,$contract_sn);
        }



        $result = Db::name('contract')->alias('c')
            ->leftJoin('dj_asset f','c.contract_enclosure_file_id  = f.id')
            ->leftJoin('dj_asset ff','c.supplement_file_id  = ff.id')
            ->field('c.*,f.filename contract_enclosure_file_name,ff.filename supplement_file_name')
            ->where(['order_id'=>$order_id])->find();

        $contract_sn = $result['contract_sn'];
        $file = json_decode($result['contract_file'],true);
        $keep_record_time =  date('Y-m-d H:i',$result['keep_record_time']);
        $sign_time =  date('Y-m-d',$result['sign_time']?$result['sign_time']:time());
        $file =  ContractModel::content_temp($data['order_id'],$contract_sn,$result['sign_time']);
        $order_info = Db::name("order")->where(['order_id'=>$data['order_id']])->find();
        $site_domain = cmf_get_domain().'/';
        $this->assign("add_order_time",$keep_record_time);
        $this->assign("sign_time",$sign_time);
        $this->assign("order_id", $data['order_id']);
        $this->assign("order_id", $data['order_id']);
        $this->assign([
            'result'=>$result,
            'contract_sn'=>$contract_sn,
            'file'=>$file,
            'customer_id' => $data['customer_id'],
            'json_file'=>json_encode($file),
            'tomb_num'=>$order_info['tomb_num'],
            'file_html'=>$site_domain.cmf_get_image_preview_url($file['html']),
            'file_docx'=>$site_domain.cmf_get_image_preview_url($file['doc'])
        ]);
		return $this->fetch();
	}

    /*订单*/
    public function Orderpay($ajax=0){
        if ($this->request->isPost()){
            $param = $this->request->param();
            if (empty($param['real_name'])){
                $this->error('请填写付款人姓名');
            }

            if (empty($param['real_phone'])){
                $this->error('请填写付款人联系方式');
            }
            if (!cmf_check_mobile($param['real_phone'])){
                $this->error('请填写付款人手机号错误！');
            }
            $goods_price_num=0;
            if (isset($param['goods'])){
                foreach ($param['goods'] as $k=>&$val){
                    OrderGoodsModel::update(['discount_price'=>$val['discount_price'],'total_price'=>$val['total_price']],['id'=>$k]);
                    $goods_price_num+=$val['total_price'];
                }
            }
            $pay_ins = [
                'type'=>2,
                'itype'=>0,
                'order_id'=>$param['order_id'],
                'pay_sn'=>OrderPayLogModel::getselfPayNum('add_time','pay_sn','JS'),
                'tomb_id'=>$param['tomb_id'],
                'tomb_num'=>$param['tomb_num'],
                'tom_price'=>$param['tom_price'],//购墓价格
                'discount_rate'=>$param['discount_rate'],//折扣
                'deal_price'=>$param['deal_price'],//成交
                'free_price'=>$param['free_price'],//减免金额
                'deposit_price'=>$param['deposit_price'],//定金
                'total_price'=>$param['total_price'],//应收金额
                'goods_price'=>$goods_price_num,//$param['goods_price'],//应收金额
                'real_name'=>$param['real_name'],//付款人
                'real_phone'=>$param['real_phone'],//付款人
                'pay_type'=>$param['pay_type'],//付款方式
                'remark'=>$param['remark'],//备注
                'add_time'=>time(),//备注
                'handle'=>cmf_get_current_admin_id(),//收款人
                'pay_real_name'=>cmf_get_current_admin_id(),//收款人
                'customer_id'=>$param['customer_id'],//收款人
                'status'=> 0,// 付款方式
            ];

//            if ($param['tomb_type']==1){
//                $ins['free_price']=$param['free_price'];//免
//            }elseif ($param['tomb_type']==2){
//                $ins['deposit_price_two']=$param['deposit_price_two'];//定金2
//            }

            if ($param['pay_id']){
                $rets = OrderPayLogModel::where(['id'=>$param['pay_id']])->update($pay_ins);
            }else{
                $rets =  OrderPayLogModel::insertGetId($pay_ins);
            }
            if ($rets != false){
                OrderModel::update(['status'=>1],['order_id'=>$param['order_id']]);
                $this->success('提交成功',url('orders/visua'));
            }else{
                $this->success('提交失败，请检查填写内容');
            }
        }

        $data = $this->request->param();
        $order_id =  $data['order_id'];

        $is_ht =  Db::name('contract')->where(['order_id'=>$order_id])->find();
        if ($ajax==1){
            if (empty($is_ht['contract_enclosure'])){
                return $this->error('上传签章合同后请先保存然后点击下一步！');
            }
//            if (empty($is_ht['supplement'])){
//                return $this->error('请上传合同附件！请先保存');
//            }
            return $this->success('');
        }

        $result_order = Db::name('order')->alias('o')->field('o.*,p.*,c.reacher')
            ->join("dj_tombarea_row_col c","o.tomb_id = c.colID")
            ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id","left")
            ->where(['o.order_id'=>$order_id])->find();

        $result_order['tomb_regulation'] = $this->regulation_arr[$result_order['tomb_regulation']];
        $result_order['pro_status'] = $this->col_status[$result_order['pro_status']];
        $result_order['add_time'] = date('Y-m-d H:i:s',$result_order['add_time']);//$result_order['pro_status']];
        $result_order['tomb_type_name'] = $this->cate_arr[$result_order['tomb_type']];

        $result_customer = CustomerInfoModel::where('id',$result_order['customer_id'])->find();

        $pd_pl_where=[
            'pd.order_id'=>$order_id,
            'pd.customer_id'=>$result_order['customer_id'],
            'pl.customer_id'=>$result_order['customer_id'],
            'pl.status'=>1,
            'pd.dtype'=>1,
            'pd.status'=>1,
        ];
        $pd_field = 'pd.deposit_sn,pd.status,pd.handle,pd.dtype,pd.refund_state';
        $pd_field .= ',pl.pay_sn,pl.real_name,pl.add_time,pl.deposit_price,pl.pay_type,pl.pay_real_name,pl.type,pl.refund_state';
        $result_deposit = Db::name('pay_deposit')->alias('pd')->field($pd_field)
            ->join('dj_order_pay_log pl','pd.pay_id = pl.id')
            ->where($pd_pl_where)->select();
        $deposit_price=0;
        foreach ($result_deposit as $kdep=>&$vdep){
            if ($vdep['refund_state']==0){
                $deposit_price+=$vdep['deposit_price'];
            }else{
//                $deposit_price-=$vdep['deposit_price'];
            }
        }

        $result_goods = Db::name('order_goods')->where(['customer_id'=>$result_order['customer_id'],'order_id'=>$order_id])->select();
        $goods=[];
        $goods_total_price=0;
        foreach ($result_goods as $k=>&$valg){
                $cate_name = Db::name('goods')->alias('g')->field('c.cate_name')
                    ->join('dj_cate c','c.id = g.cate_p_id','left')
                    ->where('g.id',$valg['goods_id'])->find();
                $info['id'] = $valg['id'];
                $info['goods_id'] = $valg['goods_id'];
                $info['goods_name'] = $valg['goods_name'];
                $info['goods_price'] = $valg['goods_price'];
                $info['num'] = $valg['num'];
                $info['cate_name'] = $cate_name['cate_name'];
                $info['total_price'] = $valg['num']*$valg['goods_price'];
                $info['add_user'] = $valg['add_user'];
                $goods[] = $info;
                $goods_total_price+=$info['total_price'];
        }

        $result_order['deposit_price']  = intval($deposit_price);
        $result_order['shoppingguide_name']  = cmf_get_admin_name($result_order['shoppingguide']);
        $result_order['agent_user_name']  = cmf_get_admin_name($result_order['agent_user']);
        $result_order['handle_name']  = cmf_get_admin_name($result_order['handle']);
        $result_order['payaddtime']  = date('Y-m-d H:i:s',$result_order['sign_time']);
        $pay_info = OrderPayLogModel::where(['order_id'=>$result_order['order_id'],'tomb_id'=>$result_order['tomb_id'],'type'=>2,'status'=>0])->find();

        $this->assign([
            'pay_info'=>$pay_info,
            'result'=>$result_order,
            'customer'=>$result_customer,
            'deposit'=>$result_deposit,
            'goods_arr'=>$goods,
            'order_id'=>$order_id,
            'goods_total_price'=>$goods_total_price,
        ]);


        if ($result_order['tomb_type']==1){
            return $this->fetch('orderpay_goods');
        }elseif ($result_order['tomb_type']==2){
            return $this->fetch('orderpay_arl');
        }elseif ($result_order['tomb_type']==3){
            return $this->fetch('orderpay_ecological');
        }elseif ($result_order['tomb_type']==4){
            return $this->fetch('orderpay_goods');
        }
    }

    public  function getParent( $pid ,$array=[],$info_arr=[]) {
        static $level = 1;
        $is_parent = Db::name( 'cemetery')->where(["id"=>$pid])->find();
        $info_arr['name_'.$level] = $is_parent['name'];
        $array[] = $is_parent;
        if ( $is_parent["parent_id"] ) {
            $level++;
            return $this->getParent( $is_parent['parent_id'],$array,$info_arr);
        }
        return $info_arr;
    }

	/**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {
        if ($array[$id]['parent_id']==0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id']==$id){
            return  $i;
        }else{
            $i++;
            return $this->_get_level($array[$id]['parent_id'],$array,$i);
        }
    }

     // 墓位信息
    public function tombareacol()
    {
        $id = $this->request->param("id");
        $array_list = TombareaRowColModel::getTombRowColById($id);
        $user = Db::name("user")->where('id',cmf_get_current_admin_id())->find();
        $result['data']=$array_list;
        $result['user_if_sale']=$user['if_sale'];
        exit(json_encode($result));
    }
    //商品
    public function ajax_goods()
    {
        $cate_id = $this->request->param('cate_id');
        $where = ['d.type' => 0, 'd.is_delete' => 0, 'd.if_show' => 1, 'd.cate_p_id' => $cate_id];
        //取库房数据
        $results = Db::name("Goods")->alias("d")->field("d.id,d.goods_name,d.price,d.photos_url,stock,c.cate_name")
            ->join("dj_cate c", "c.id = d.cate_p_id", "left")
            ->join("dj_room r", "r.id = d.room", "left")
            ->where($where)->order('d.id', 'DESC')->select();
        $this->result($results);
    }

    /**
     *  保留
     */
    public function tombareacolretain(){
        $param = $this->request->param();
        $status = true;
        $col_id = explode(',', $param['id']);
        foreach ($col_id as $k=>&$value) {
            $res_info = Db::name('tombarea_row_col')->where(['colID' => $value])->find();
            if ($res_info) {
                if ($res_info['col_status'] != 6 || $res_info['col_status'] != 7 ) {
                    $msg_[$k + 1] = 1;
                    $res1 = Db::name('tombarea_row_col')->where(['colID' => $value])->update(['col_status' =>2]);
                    if(!$res1) {
                        $status = false;
                    }
                }
            }
        }
        if( $status){
            $this->success('保留成功',url('visua'));
        }else{
            $this->error('保留失败');
        }
    }
    /**
     * 取消保留
     */
    public function tombCancelReservation(){
        $param = $this->request->param();
        $status = true;
        $col_id = explode(',', $param['id']);
        foreach ($col_id as $k=>&$value) {
            $info = Db::name('tombarea_row_col')->where(['colID' => $value])->find();
            $product_info = Db::name('tombarea_product')->where(['tombar_id' => $info['rowid']])->find();
            if ($info){
                if ($info['col_status'] != 6 || $info['col_status'] != 7 ) {
                    if ($product_info) {
                        Db::name('tombarea_row_col')->where(['colID' => $value])->update(['col_status' => 1]);
                    } else {
                        Db::name('tombarea_row_col')->where(['colID' => $value])->update(['col_status' => 0]);
                    }
                }else{
                    $status = false;
                }
            }
        }
        if( $status){
            $this->success('取消保留成功',url('visua'));
        }else{
            $this->error('取消保留失败！');
        }
    }

    public function getSupName($id){
        // 拼接查询条件hql
        $res=Db::name("cemetery")->where(array('is_delete'=>0,'id'=>$id))->field('id,name,type,parent_id')
            ->select()->toArray();
        // 得到一级数据
        if($res) {
            if($res[0]["parent_id"] != 0) {
                $result = $this->getSupName($res[0]["parent_id"]);
            }else{
                $result = array();
            }
            $imgInfo = array_merge_recursive($res, $result);
        }else{
            $imgInfo = array();
        }
        return $imgInfo;
    }

    public function getSup($id){
        // 拼接查询条件hql
        $res=Db::name("cemetery")->where(array('is_delete'=>0,'id'=>$id))
            ->select()->toArray();
        // 得到一级数据
        if($res) {
            if($res[0]["parent_id"] != 0) {
                $result = $this->getSup($res[0]["parent_id"]);
            }else{
                $result = array();
            }
            $imgInfo = array_merge_recursive($res, $result);
        }else{
            $imgInfo = array();
        }
        return $imgInfo;
    }

    public function gaopaiyi(){

        return $this->fetch();
    }

    public function this_tomb(){
        $queue_regulation = config('queue.regulation');
        $queue_convergence = config('queue.convergence');
        $queue_funeral = config('queue.funeral');
        $queue_periphery = config('queue.periphery');
        $this->assign('tomb_regulation',$queue_regulation);
        $this->assign('tomb_funeral',$queue_funeral);
        $this->assign('tomb_convergence',$queue_convergence);
        $this->assign('tomb_periphery',$queue_periphery);
    }

}
